<?php
namespace app\admin\controller;
use think\facade\Db;
use app\__MODULE__\model\{SurveyQuestion,SurveyOption,SurveyAnswer,SurveyTheme,User};
use app\common\BaseController;

class Survey extends BaseController{
    

    /**
     * 问卷主题
     * @return void
     * @author Sam
     * date 2021-09-08
     */
    public  function survey_theme(){
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $where = [];
        if(isset($search['title']) && $search['title'] !=''){
             $where[] = ['title','like',"%{$search['title']}%"];
        }
        $query  = SurveyTheme::where($where);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('sort desc,id desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    /**
     * 主题添加
     * @return void
     * @author Sam
     * date 2021-09-08
     */
    public function survey_theme_create(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'title' => 'require',
            ], [
                'title.require'      => '标题不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        if(SurveyTheme::create($data)) json_response(1,'操作成功');
            json_response(0,'操作失败');
         
    }

        /**
     * 主题编辑
     * @return void
     * @author Sam
     * date 2021-09-08
     */
    public function survey_theme_edit(){
        $id = param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            if(SurveyTheme::update($data,['id'=>$id])) json_response(1,'操作成功');;
            json_response(0,'操作失败');
         }else{
             $data = SurveyTheme::find($id);
            return $this->render_form([
                ['type'=>'text', 'name'=>'title', 'title'=>'标题', 'lay-verify'=>'required'],
                ['type'=>'text', 'text_type'=>'number','name'=>'sort', 'title'=>'排序'],
            ],$data);
         }
    }

        /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function survey_theme_detail(int $id): \think\response\Json
    {
        try {
            $row  = SurveyTheme::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }


            /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function survey_question_detail(int $id): \think\response\Json
    {
        try {
            $row  = SurveyQuestion::with(['option'])->where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }
    /**
     * 主题删除
     * @return void
     * @author Sam
     * date 2021-09-08
     */
    public function survey_theme_delete(){
        $ids = param_check('ids');
        if(request()->isPost()) {
            $data = SurveyTheme::where('id','in',$ids)->select();
            if($data->delete()) \json_response(1,'操作成功');
            \json_response(0,'操作失败');
         }
    }
    /**
     * 题目首页
     */
    public function survey_question_index(){
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $where = [];
        if(isset($search['title']) && $search['title'] !=''){
             $where[] = ['title','like',"%{$search['title']}%"];
        }
        $query  = SurveyQuestion::with('survey')->where($where);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        if(count($data)){
            foreach($data as $v){
                $status = [1=>'单选',2=>'多选',3=>'填空',4=>'选择填空'];
                $v['type_text'] = $status[$v['type']];
            }
        }
        $survey = SurveyTheme::field('id,title')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
            'survey'=>$survey
        ]);
    }

        /**
     * 批量导入
     * @return void
     * @author Sam
     * date 2021-07-02
     */
    public function import(){
        $survey_id = \param_check('id');
        set_time_limit(0);
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $data = big_csv_to_array($_FILES['file']['tmp_name']);
        $type_option = ['单选' => 1,'多选' => 2,'填空' => 3, '选择填空' => 4];
        $num = 0;
        foreach ($data as $k=>$value) {
            if($k == 0) continue;
            if(!empty($value[0])) {
                 if($value[0] == '' || !isset($value[0])){
                    json_response(0,'标题不得为空');
                }
                if($value[1] == '' || !isset($value[1])){
                    json_response(0,'类型不得为空');
                }
                if(trim($value[1]) == '单选' || trim($value[1]) == '多选' ){
                    //选择题目没有选项报错
                    if(!$value[2] && !$value[3] && !$value[4]&& !$value[5]&& !$value[6]&& !$value[7]){
                        json_response(0,'选择题至少填写一个选项');
                    }
                }
                if(SurveyQuestion::where(['title'=>$value[0]])->count()){
                    continue;
                }
                Db::startTrans();
                try {
                    $survey_question =  SurveyQuestion::create([
                        'survey_id' => $survey_id,
                        'title' => trim((string)$value[0]),
                        'type' => trim((int)$type_option[$value[1]])
                    ]);
                    $insert_data = ['A'=>$value[2],'B'=>$value[3],'C'=>$value[4],'D'=>$value[5],'E'=>$value[6],'F'=>$value[7]];
                    foreach($insert_data as $k=>$v){
                        if(trim($v) != '' && $v){
                            SurveyOption::create([
                                'question_id' => $survey_question->id,
                                'option_name' => $v,
                                'option_number'  => $k 
                            ]);
                        }
                    }
                     $num += 1;
                    Db::commit();
                 } catch (\Exception $e) {
                    Db::rollback();
                    $num = 0;
                    json_response(0,$e->getMessage());
                 }
               
            }
        }
        json_response(1,"成功导入{$num}条数据");
    }

    /**
     * 答题记录
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public function survey_record(){       
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $where = [];
        if(isset($search['title']) && $search['title'] !=''){
            $where[] = ['question_name','like',"%{$search['title']}%"];
        }
        if(isset($search['user']) && $search['user'] !=''){
            $ids = User::where('mobile|nickname','like',"%{$search['user']}%")->column('id');
            if($ids && is_array($ids)){
                $where[] = ['uid','in',$ids];
            } 
        }
        $query  = SurveyAnswer::with(['question','user','survey'])->where($where);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
    
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    public function survey_export(){
        $search = request()->param();
        $where = [];
        if(isset($search['title']) && $search['title'] !=''){
            $where[] = ['question_name','like',"%{$search['title']}%"];
        }
        if(isset($search['user']) && $search['user'] !=''){
            $ids = User::where('mobile|nickname','like',"%{$search['user']}%")->column('id');
            if($ids && is_array($ids)){
                $where[] = ['uid','in',$ids];
            } 
        }
        $query  = SurveyAnswer::with(['question','user','survey'])->where($where);
        \big_array_to_csv($query,'答题记录',[
            'user_name'=>['用户名',function($row){{
                return $row['user']['nickname'];
            }}],
            'survey_title'=>'主题',
            'question_name'=>'题目',
            'answer_name'=>'答案',
            'create_time'=>'答题时间',
        ]);

    }

    /**
     * 下载模板
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public function down_temp(){
      header("Location:https://game.vrupup.com/resources/sam_base/survey.csv");
      exit();
    }



        /**
     * 添加
     * @return void
     * @author 
     * date 
     */
    public function survey_question_create(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'title' => 'require',
                'type' => 'require',
                'survey_id' => 'require',
            ], [
               'title.require'       => '标题不得为空',
               'type.require'       => '类型不得为空',
               'survey_id.require'       => '请选择问卷',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
          if($data['type'] !=3){
              //非填空题
              if($data['type'] == 4 && !in_array('其他',array_column($data['option'],'option_name'))){
                json_response(0,'选择填空选项必须包含 ‘其他’ ');
            }else{
                foreach ($data['option'] as $key => $value) {
                    if(trim($value['option_number']) == '' || trim($value['option_name']) == ''){
                        json_response(0,'请完善选项');
                    }
                    if(\in_array(trim($value['option_number']),['A','B','C','D','E']) == false){
                        json_response(0,'选项必须为A,B,C,D,E等勿加空格');
                    }
                }
            }
          }else{
              unset($data['option']);
          }
          if(SurveyQuestion::where('title',$data['title'])->count()){
             json_response(0,'该题目已存在');
        }
        Db::startTrans();
        try {
           $question =  SurveyQuestion::create([
                'survey_id' => $data['survey_id'],
                'type'      => $data['type'],
                'title'     => $data['title']
            ]);
            if($data['type'] !=3 && $data['option']){
                foreach ($data['option'] as $key => $value) {
                    SurveyOption::create([
                        'survey_id'   =>$question->survey_id,
                        'question_id' => $question->id,
                        'option_name' => $value['option_name'],
                        'option_number' => $value['option_number'],
                    ]);
                }
            }
           Db::commit();
        } catch (\Exception $e) {
           Db::rollback();
           json_response(0,$e->getMessage());
        }
        json_response(1,'添加成功');
    }

        /**
     * 删除选项
     * @return void
     * @author Sam
     * date 2021-02-26
     */
    public function del_option(){
        if(request()->isPost()){
            $id       = request()->post('id/d');
            if($option = SurveyOption::find($id)){
                if($option->delete()){
                    json_response(1,'删除成功');
                }else{
                    json_response(0,'删除失败');
                }
            }else{
                json_response(0,'无此选项记录');
            }
        }else{
            json_response(0,'非法请求');
        }
    }

    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function survey_question_edit(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'id' => 'require',
                'title' => 'require',
                'type' => 'require',
                'survey_id' => 'require',
            ], [
                'id.require'       => '缺少参数',
               'title.require'       => '标题不得为空',
               'type.require'       => '类型不得为空',
               'survey_id.require'       => '请选择问卷',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        if($data['type'] !=3){
            //非填空题
            if($data['type'] == 4 && !in_array('其他',array_column($data['option'],'option_name'))){
              json_response(0,'选择填空选项必须包含 ‘其他’ ');
          }else{
              foreach ($data['option'] as $key => $value) {
                  if(trim($value['option_number']) == '' || trim($value['option_name']) == ''){
                      json_response(0,'请完善选项');
                  }
                  if(\in_array(trim($value['option_number']),['A','B','C','D','E']) == false){
                      json_response(0,'选项必须为A,B,C,D,E等勿加空格');
                  }
              }
          }
        }else{
            unset($data['option']);
        }
        Db::startTrans();
        try {
            if(!$question = SurveyQuestion::find($data['id'])) return JsonService::fail('无此题目');
            $question->save($data);
            if($data['type'] !=3 && $data['option']){
                foreach ($data['option'] as $key => $value) {
                    if($option = SurveyOption::where('question_id',$data['id'])->where('option_number',$value['option_number'])->find()){
                        $option->option_name = $value['option_name'];
                        $option->option_number = $value['option_number'];
                        $option->save();
                    }else{
                        SurveyOption::create([
                            'question_id' => $question->id,
                            'option_name' => $value['option_name'],
                            'option_number' => $value['option_number'],
                        ]);
                    }
                  
                }
            }
           Db::commit();
        } catch (\Exception $e) {
           Db::rollback();
           json_response(0,$e->getMessage());
        }
        json_response(1,'编辑成功');
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function survey_question_delete(){
        $ids = param_check('ids');
        if(!$SurveyModel = SurveyQuestion::where('id','in',$ids)->select()) json_response(0,'不存在');
        if($SurveyModel->delete()){
            SurveyOption::where('question_id','in',$ids)->delete();
            json_response(1,'操作成功');
        } 
        json_response(0,'操作失败');
    }

}